package com.wingsboat.sort;

/**
 * @author wangzhong
 * @description: 快速排序---轴排序
 * @date 2024/7/21 13:22
 */
public class QuickSort {

    public static void main(String[] args) {
        int[] arr = {5,2,7,0,8,6,3,1,2};
        QuickSort.sort(arr);
        for (int i : arr) {
            System.out.println(i);
        }
    }

    public static void sort(int[] arr){
        quickSort(0,arr.length-1,arr);
    }

    private static void quickSort(int left, int right, int[] arr) {
        if (left < right) {
            int pivotIndex = partition(left, right, arr);
            quickSort(left, pivotIndex - 1, arr);
            quickSort(pivotIndex + 1, right, arr);
        }
    }

    private static int partition(int left, int right, int[] arr) {
        int pivot = arr[left];
        int low = left + 1;
        int high = right;

        while (true) {
            while (low <= high && arr[low] <= pivot) {
                low++;
            }
            while (low <= high && arr[high] > pivot) {
                high--;
            }
            if (low <= high) {
                swap(low, high, arr);
            } else {
                break;
            }
        }

        swap(left, high, arr);
        return high;
    }

    public static void swap(int a,int b,int[] arr){
        int temp = arr[a];
        arr[a] = arr[b];
        arr[b] = temp;
    }

}
